<template>
  <BaseDialog
    :title="(!props.item.communityId ? '新增' : '编辑') + '片区/村社'"
    :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible"
    width="800px"
  >
    <!-- <BaseForm
      type="rule"
      :handleOk="handleOk"
      :handleCancel="handleCancel"
      :items="formItems"
      v-model:form="ruleForm"
      :rules="rules"
      label-width="100px"
      :refresh="handleSearch"
    >
    </BaseForm> -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      style="padding: 16px 16px 0 16px"
      @submit="submitForm"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="片区/村社名称" prop="communityName">
        <el-input style="width: 546px" v-model="ruleForm.communityName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-row :gutter="10" v-for="(dto, index) in ruleForm.communityAreaDtoList" :key="dto.uid">
        <el-col :span="22">
          <el-form-item :label="index == 0 ? '所属台区' : ''">
            <new-select-area
              :powerId="dto.powerId"
              :item="dto"
              :lineId="dto.lineId"
              :areaId="dto.areaId"
              @change="(val) => handleChange(val, index)"
            >
            </new-select-area>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-link :underline="false" link type="danger" size="small" @click.prevent="handleLineDel(index)"
            >删除
          </el-link>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 18px">
        <el-col :offset="5" :span="16">
          <el-button style="width: 100%" type="primary" @click="handleAddLine()">
            <el-icon>
              <Plus />
            </el-icon>
            增加台区
          </el-button>
        </el-col>
      </el-row>
      <el-form-item label="行政区划">
        <SelectSite
          width="180.5px"
          v-model:form="ruleForm"
          :getData="commonService.getDistrictList"
          :keys="keys"
        ></SelectSite>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input
          style="width: 545px"
          v-model="ruleForm.address"
          placeholder="请输入"
          :autosize="{ minRows: 4, maxRows: 6 }"
          type="textarea"
          maxlength="300"
          show-word-limit
        ></el-input>
      </el-form-item>
      <div class="form-btn">
        <slot name="prefix-button" />
        <el-button @click="handleCancel"> 取 消</el-button>
        <el-button type="primary" :loading="loading" native-type="submit"> 确 定 </el-button>
        <slot name="suffix-button" />
      </div>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import BaseForm from '@/components/base-form.vue';
import BaseDialog from '@/components/base-dialog.vue';
import { basicConfigService } from '@/api/basicConfig';
import { commonService } from '@/api/common';
import selectArea from '@/components/selectArea.vue';
import openMsgBox from '@/hooks/messageBox.js';
import type { FormInstance } from 'element-plus';

const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  areaList: {
    type: Object,
  },
  powerSupplyIdList: {
    type: Object,
  },
});
const emit = defineEmits(['update:dialogVisible']);
const formItems = ref([
  {
    name: '行政区划',
    keys: {
      provinceId: '',
      cityId: '',
      regionId: '',
    },
    // required: true,
    clearable: true,
    type: 'selectSite',
    getData: commonService.getDistrictList,
  },
  {
    name: '详细地址',
    key: 'address',
    clearable: true,
    type: 'textarea',
    maxlength: '300',
    'show-word-limit': true,
  },
]);
const keys = ref({
  provinceId: '',
  cityId: '',
  regionId: '',
});
const rules = reactive({
  communityName: [{ required: true, message: '请输入', trigger: 'change' }],
  //areaId: [{ required: true, message: '请选择', trigger: 'change' }],
  provinceId: [{ required: true, message: '请选择', trigger: 'change' }],
  cityId: [{ required: true, message: '请选择', trigger: 'change' }],
  regionId: [{ required: true, message: '请选择', trigger: 'change' }],
});
const ruleForm = ref({
  communityId: '',
  communityName: '',
  areaId: '',
  provinceId: '',
  cityId: '',
  regionId: '',
  address: '',
  communityAreaDtoList: [],
});
const handleOk = () => {
  if (props.item.communityId) {
    return basicConfigService.communityUpdate({
      data: { ...ruleForm.value },
    });
  } else {
    return basicConfigService.communityBatchSave({
      data: [{ ...ruleForm.value }],
    });
  }
};
const handleCancel = () => {
  emit('update:dialogVisible', false);
};
onMounted(() => {
  // console.log(JSON.parse(JSON.stringify(props.item)), 'props.item');
  if (props.item.communityId) {
    ruleForm.value.communityId = props.item.communityId;
    ruleForm.value.communityName = props.item.communityName;
    ruleForm.value.provinceId = props.item.provinceId;
    ruleForm.value.cityId = props.item.cityId;
    ruleForm.value.regionId = props.item.regionId;
    ruleForm.value.address = props.item.address;
    ruleForm.value.areaId = props.item.areaId;
    ruleForm.value.communityAreaDtoList =
      props.item.communityAreaResDtoList && props.item.communityAreaResDtoList.length > 0
        ? props.item.communityAreaResDtoList.map((n) => {
            return {
              powerId: n.powerId,
              powerName: n.powerName,
              powerCode: n.powerCode,
              lineId: n.lineId,
              lineName: n.lineName,
              lineCode: n.lineCode,
              areaCode: n.areaCode,
              areaId: n.areaId,
              areaName: n.areaName,
              id: n.id,
              uid: n.id,
            };
          })
        : [];
  }
});

const handleChange = (val, index) => {
  console.log(val, 'val');
  const key = val.key;
  if (key === 'powerId') {
    ruleForm.value.communityAreaDtoList[index].lineId = '';
    ruleForm.value.communityAreaDtoList[index].lineName = '';
    ruleForm.value.communityAreaDtoList[index].areaId = '';
    ruleForm.value.communityAreaDtoList[index].areaName = '';
  }
  if (key === 'lineId') {
    ruleForm.value.communityAreaDtoList[index].areaId = '';
    ruleForm.value.communityAreaDtoList[index].areaName = '';
  }
  if (val.item) {
    ruleForm.value.communityAreaDtoList[index][val.name] = val.item[val.name];
    ruleForm.value.communityAreaDtoList[index][key] = val.item[key];
  } else {
    ruleForm.value.communityAreaDtoList[index][val.name] = '';
    ruleForm.value.communityAreaDtoList[index][key] = '';
  }
};

const handleAddLine = () => {
  const uid = ruleForm.value.communityAreaDtoList.length;
  ruleForm.value.communityAreaDtoList.push({ uid });
};
const handleLineDel = (index) => {
  openMsgBox(
    {},
    () => {
      ruleForm.value.communityAreaDtoList.splice(index, 1);
    },
    () => {
      //handleSearch()
    },
  );
};
const ruleFormRef = ref<FormInstance>();
const loading = ref(false);
const submitForm = (e) => {
  e.preventDefault();

  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let emptyList = ruleForm.value.communityAreaDtoList.find((n) => !n.lineId || !n.powerId || !n.areaId);
      if (emptyList) {
        ElMessage({
          message: '供电单位,供电线路,台区不能为空',
          type: 'error',
        });
        return;
      }
      let list = ruleForm.value.communityAreaDtoList.map((n) => {
        return n.powerId + '-' + n.lineId + '-' + n.areaId;
      });
      if (list.length > [...new Set(list)].length) {
        ElMessage({
          message: '存在重复数据请检查',
          type: 'error',
        });
        return;
      }
      loading.value = true;
      if (ruleForm.value.communityId) {
        basicConfigService
          .communityUpdate({
            data: {
              ...ruleForm.value,
            },
          })
          .then((res) => {
            handleCancel();
            props.handleSearch();
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        basicConfigService
          .communityBatchSave({
            data: [{ ...ruleForm.value }],
          })
          .then((res) => {
            handleCancel();
            props.handleSearch();
          })
          .catch(() => {
            loading.value = false;
          });
      }
    } else {
    }
  });
};
</script>

<style lang="scss" scoped></style>
